#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
#Copyright (c) 2009 Timothe Faudot

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
"""

"""
A module with helpers method to analyze a script file
"""

#music
import audiere

#other stuff
import os
import sys
import inspect


#example of rejected method or class names which will not be taken into account
rejectedMethodNames = ["__init__"]
rejectedClassNames = []

def parse(module, codeLines):
    """
    parse a file and modify the code lines with the functions/methods
    augmented with their respective frequency and duration determined by
    the roughly estimated number of appearance(!=calls!!!) and the number
    of lines of code
    """
    #a list containing all the wanted insertions,
    #we don't do it live because the returned lines by the getsourcelines
    #woule become incorrect. Instead we do it all at the end, backward.
    insertions = []
    moduleClasses = getModuleClasses(module)
    #print "--------module classes--------:"
    #print moduleClasses
    #print "--------classes methods--------:"
    for cls in moduleClasses:
        #print cls,":"
        meths = getMethods(cls)
        for met in meths:
            #we take only the methods defined in the user's imported module
            if inspect.getmodule(met)==module:
                metSource, sourceLine = inspect.getsourcelines(met)
                sourceLength = len(metSource)
                numberOfCalls = sum([line.count(met.__name__+"(") for line in codeLines])
                #print "%s : %d lines long \t situated at line%s \t and appears %d times"%(met.__name__, sourceLength, sourceLine, numberOfCalls)
                insertions.append((sourceLine, sourceLength, numberOfCalls, met.__name__))
    #insetions in to the codeLines, backward
    print insertions
    insertions.sort(reverse=True)
    print insertions
    for insert in insertions:
        indentation = 0
        while codeLines[insert[0]-1][indentation]==" ": indentation+=1
        #print codeLines[insert[0]-1],"has an indentation of ", indentation
        codeLines.insert(insert[0]-1, "%s@soundDecorator(freq=%f, duration=%f)#%s\n"%(" "*indentation, insert[1], insert[2], insert[3]))

def getMethods(cls):
    return [met for met in cls.__dict__.values() if callable(met) and met.__name__ not in rejectedMethodNames]

def getModuleClasses(module):
    return [cls for cls in module.__dict__.values() if inspect.isclass(cls) and cls not in rejectedClassNames]


if __name__=="__main__":
    #scriptFileName = "testScript.py"
    try: scriptFileName=sys.argv[1]
    except:
        print "usage: py2wav.py <your_script_name.py> [(your_script_args)*]"
        sys.exit(-1)
    
    #init
    #scriptFileName = "testScript.py"
    scriptName = scriptFileName.replace(".py","")
    outputScriptFileName = scriptName+"_oke.py"
    
    module = __import__(scriptName)
    
    #parsing the file
    scriptFile = open(scriptFileName, "r")
    scriptLines = scriptFile.readlines()
    parse(module, scriptLines)
    
    #add the decoration code at the beginning
    scriptLines.insert(0,
"""
d = audiere.open_device()
from time import sleep
#decorator looks like this: @soundDecorator(freq=440.0, duration=1.0)
def soundDecorator(freq, duration):
    def decorator(target):
        def wrapper(*args, **kwargs):
            t = d.create_tone(freq*100)
            t.play()
            print "Playing freq %f for %fs before the execution of %s"%(freq, duration, target.__name__)
            sleep(duration/100)
            t.stop()
            return target(*args, **kwargs)
        return wrapper
    return decorator
""")
    
    #writing the result
    outputScriptFile = open(outputScriptFileName, "w")
    outputScriptFile.writelines(scriptLines)
    outputScriptFile.close()
    
    #launch the script
    args = [outputScriptFileName]+sys.argv[2:]
    print args
    execfile(outputScriptFileName)